﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using DevExpress.XtraEditors;
using XCT.Class;
using XCT.Functions;

namespace XCT.Forms
{
    public partial class FormEDC : DevExpress.XtraEditors.XtraForm
    {
        public FormEDC()
        {
            InitializeComponent();
        }

        private FormMain formMain;
        public FormEDC(FormMain formMain)
        {
            InitializeComponent();
            this.formMain = formMain;
        }

        #region "Biến"

        clsEDC clsedc = new clsEDC();
        clsDungChung clsdc = new clsDungChung();
        string pTuanKH, pMaMau_SP = "";
        int intTrangThai = -1; // 0:Them, 1:Sua, 2:Xoa
        DataSet dtsNhapEDC, dtsXemEDC;
               
        #endregion

        #region "Sự Kiện"

        #region "Dùng Chung"

        private void FormEDC_Load(object sender, EventArgs e)
        {
            fKhoiTaoComBo();
        }

        private void FormEDC_FormClosed(object sender, FormClosedEventArgs e)
        {
            formMain.pFormEDC = null;
        }

        private void FormEDC_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Modifiers == Keys.Control)
                {
                    switch (e.KeyCode)
                    {
                        case Keys.S:
                            if (tabEDC.SelectedTabPage.Name == "tabEDC1")
                            {
                                if (intTrangThai != -1)
                                    if (XtraMessageBox.Show("Bạn có chắc muốn lưu không ?", "Thông tin lưu ý: ", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                    {
                                        grdNhapEDC_View.FocusedRowHandle = grdNhapEDC_View.FocusedRowHandle + 1;
                                        grdNhapEDC_View.CloseEditor();
                                        if (fLuuEDC() == true)
                                        {
                                            XtraMessageBox.Show("Lưu thành công !", "Thông báo:");
                                            intTrangThai = -1;
                                            fDocChietTinhEDCTheoLSX_MauSP(lupLSX.Text, pMaMau_SP, dteNgayTH.Text);
                                        }
                                        else
                                        {
                                            XtraMessageBox.Show("Không thể lưu, vui lòng kiểm tra lại dữ liệu nhập!");
                                        }
                                    }
                            }
                            return;
                        case (Keys.E):
                            if (tabEDC.SelectedTabPage.Name == "tabEDC1")
                            {
                                if (intTrangThai == -1 || intTrangThai == 1)
                                {
                                    ArrayList arr = new ArrayList();
                                    arr.Add("SL_Nhap_Ca1"); //cột sản lượng ca 1
                                    arr.Add("SL_Nhap_Ca2"); //cột sản lượng ca 2
                                    arr.Add("SL_Nhap_Ca3"); //cột sản lượng ca 3
                                    arr.Add("GhiChu"); //ghi chú

                                    clsdc.editGrid(grdNhapEDC_View, true, arr);
                                    fMoKhoaControl(false);

                                    intTrangThai = 1;
                                    lblMsg.Text = "Bạn đang ở chế độ sửa, vui lòng nhấn [Ctrl+S] để lưu !"; lblMsg.Visible = true;
                                }
                                else
                                {
                                    XtraMessageBox.Show("Bạn phải lưu trước khi chuyển thao tác mới...", "Thông Báo:");
                                }
                            }
                            return;
						case (Keys.P):
                            if (XtraMessageBox.Show("Bạn có chắc muốn xuất ra tập tin Excel ?", "Thông tin lưu ý: ", MessageBoxButtons.YesNo) == DialogResult.Yes) 
                                XuatTapTinExcel(tabEDC.SelectedTabPage.Name);
                            return;
                    }
                }
                else if (e.KeyCode == Keys.F5)
                {
                    intTrangThai = -1;
                    if (tabEDC.SelectedTabPage.Name == "tabEDC1")
                    {
                        fDocChietTinhEDCTheoLSX_MauSP(lupLSX.Text, pMaMau_SP, dteNgayTH.Text); 
                    }
                }
                else if (e.KeyCode == Keys.Escape)
                {
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        //Sự kiện SelectedIndexChanged của cmbTuanKH, cmbThangKH, cmbNamKH
        private void cmbNamKH_SelectedIndexChanged(object sender, EventArgs e)
        {
            pTuanKH = cmbTuanKH.Text + cmbThangKH.Text + cmbNamKH.Text;
            if (tabEDC.SelectedTabPage.Name == "tabEDC1")
            {
                fDocLSXTheoTuanKH(pTuanKH);
                //fDocMauChietTinhTheoLSX(lupLSX.Text);
                //fDocChietTinhEDCTheoLSX_MauSP(lupLSX.Text, pMaMau_SP, dteNgayTH.Text);
            }
            else if (tabEDC.SelectedTabPage.Name == "tabEDC2")
            {
                fDocLSX_EDCTheoTuanKH(pTuanKH);
                //fDocMauSP_EDCTheoLSX(lupLSX.Text);
                //fDocEDCTheoLSX_MauSP(lupLSX.Text, pMaMau_SP);
            }
            lupLSX_EditValueChanged(sender, e);
        }

        //Tìm LSX
        private void txtTimLSX_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (txtTimLSX.Text.Length > 0)
                {
                    DataSet ds = new DataSet();
                    clsedc.SoLSX = txtTimLSX.Text.Trim();
                    ds = clsedc.TimLSX(tabEDC.SelectedTabPage.Name);
                    lupLSX.Properties.DataSource = ds.Tables[0].DefaultView;
                    lupLSX.Properties.ValueMember = "SoLSX";
                    lupLSX.Properties.DisplayMember = "SoLSX";
                    lupLSX.ItemIndex = 0;
                    lupLSX_EditValueChanged(sender, e);

                    if (lupLSX.ItemIndex != -1)
                    {
                        cmbTuanKH.EditValue = lupLSX.GetColumnValue("TTN").ToString().Substring(0, 2);
                        cmbThangKH.EditValue = lupLSX.GetColumnValue("TTN").ToString().Substring(2, 2);
                        cmbNamKH.EditValue = lupLSX.GetColumnValue("TTN").ToString().Substring(4, 4);
                    }
                }
            }
        }
                
        //Sự kiện EditValueChanged của lupLSX
        private void lupLSX_EditValueChanged(object sender, EventArgs e)
        {
            if (lupLSX.ItemIndex == -1 )
                lblMaSP.Text = "Mã sản phẩm";
            else
                lblMaSP.Text = lupLSX.GetColumnValue("MaSP").ToString();

            if (tabEDC.SelectedTabPage.Name == "tabEDC1")
            {
                fDocMauChietTinhTheoLSX(lupLSX.Text);
                fDocChietTinhEDCTheoLSX_MauSP(lupLSX.Text, pMaMau_SP, dteNgayTH.Text);
            }
            else if (tabEDC.SelectedTabPage.Name == "tabEDC2")
            {
                fDocMauSP_EDCTheoLSX(lupLSX.Text);
                fDocEDCTheoLSX_MauSP(lupLSX.Text, pMaMau_SP);
            }
        }        

        private void chkEdtMauSP_CheckedChanged(object sender, EventArgs e)
        {
            chkLstMauSP.BeginUpdate();
            try
            {
                for (int i = 0; i < chkLstMauSP.ItemCount; i++)
                {
                    chkLstMauSP.SetItemCheckState(i, chkEdtMauSP.CheckState);
                }
            }
            finally
            {
                chkLstMauSP.EndUpdate();
            }
        }

        //Sự kiện check list box
        private void chkLstMauSP_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            fLayGiaTriMauSP();
            if (tabEDC.SelectedTabPage.Name == "tabEDC1")
            {
                fDocChietTinhEDCTheoLSX_MauSP(lupLSX.Text, pMaMau_SP, dteNgayTH.Text);
            }
            else if (tabEDC.SelectedTabPage.Name == "tabEDC2")
            {
                fDocEDCTheoLSX_MauSP(lupLSX.Text, pMaMau_SP);
            }
            
        }

        //Sự kiện kiểm tra Tab trước khi chuyển Tab
        private void tabEDC_SelectedPageChanging(object sender, DevExpress.XtraTab.TabPageChangingEventArgs e)
        {
            if (intTrangThai != -1)
            {
                XtraMessageBox.Show("Vui lòng nhấn [Ctrl+S] để lưu trước khi chuyển tab ...", "Thông Báo:");
                e.Cancel = true;
            }
        }

        //Sự kiện chuyển Tab
        private void tabEDC_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            txtTimLSX.Text = "";
            lblMaSP.Text = "Mã sản phẩm";
            cmbNamKH_SelectedIndexChanged(sender, e);
            if (tabEDC.SelectedTabPage.Name == "tabEDC1")
            {
                dteNgayTH.Visible = true;
                labelNgayTH.Visible = true;
                //fDocLSXTheoTuanKH(pTuanKH);
                //fDocMauChietTinhTheoLSX(lupLSX.Text);
                //fDocChietTinhEDCTheoLSX_MauSP(lupLSX.Text, pMaMau_SP, dteNgayTH.Text);
            }
            else if (tabEDC.SelectedTabPage.Name == "tabEDC2")
            {
                dteNgayTH.Visible = false;
                labelNgayTH.Visible = false;
                //fDocLSX_EDCTheoTuanKH(pTuanKH);
                //fDocMauSP_EDCTheoLSX(lupLSX.Text);
                //fDocEDCTheoLSX_MauSP(lupLSX.Text, pMaMau_SP);
            }
        }

        #endregion

        #region "tabEDC1"

        //Sự kiện EditValueChanged dteNgayTH
        private void dteNgayTH_EditValueChanged(object sender, EventArgs e)
        {
            fDocChietTinhEDCTheoLSX_MauSP(lupLSX.Text, pMaMau_SP, dteNgayTH.Text);
        }

        private void repositoryItemSpinEdit1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '-')
            {
                e.Handled = true;
            }
        }

        private void grdNhapEDC_View_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            float ThucHien, LuyKe, SL_Nhap_Ca1 = 0, SL_Nhap_Ca2 = 0, SL_Nhap_Ca3 = 0;
            LuyKe = float.Parse(dtsNhapEDC.Tables[0].Rows[e.RowHandle]["LuyKe"].ToString());
            if (dtsNhapEDC.Tables[0].Rows[e.RowHandle]["SL_Nhap_Ca1"].ToString() != "")
                SL_Nhap_Ca1 = float.Parse(dtsNhapEDC.Tables[0].Rows[e.RowHandle]["SL_Nhap_Ca1"].ToString());
            if (dtsNhapEDC.Tables[0].Rows[e.RowHandle]["SL_Nhap_Ca2"].ToString() != "")
                SL_Nhap_Ca2 = float.Parse(dtsNhapEDC.Tables[0].Rows[e.RowHandle]["SL_Nhap_Ca2"].ToString());
            if (dtsNhapEDC.Tables[0].Rows[e.RowHandle]["SL_Nhap_Ca3"].ToString() != "")
                SL_Nhap_Ca3 = float.Parse(dtsNhapEDC.Tables[0].Rows[e.RowHandle]["SL_Nhap_Ca3"].ToString());
            ThucHien = float.Parse(dtsNhapEDC.Tables[0].Rows[e.RowHandle]["ThucHien"].ToString());

            if (LuyKe + SL_Nhap_Ca1 + SL_Nhap_Ca2 + SL_Nhap_Ca3 > ThucHien)
            {
                XtraMessageBox.Show("Bạn nhập vượt quá kế hoạch thực hiện !");
                grdNhapEDC_View.SetFocusedValue(0);
                grdNhapEDC_View.FocusedColumn = grdNhapEDC_View.VisibleColumns[grdNhapEDC_View.FocusedColumn.VisibleIndex - 1];
            }
        }

        #endregion

        #region "tabEDC2"


        #endregion

        #endregion

        #region "Hàm"

        #region "Dùng Chung"

        private void fMoKhoaControl(Boolean bisMoKhoa)
        {
            cmbTuanKH.Enabled = bisMoKhoa;
            cmbThangKH.Enabled = bisMoKhoa;
            cmbNamKH.Enabled = bisMoKhoa;
            lupLSX.Enabled = bisMoKhoa;
            dteNgayTH.Enabled = bisMoKhoa;
            txtTimLSX.Enabled = bisMoKhoa;
            chkEdtMauSP.Enabled = bisMoKhoa;
            chkLstMauSP.Enabled = bisMoKhoa;
        }

        private void fKhoiTaoComBo()
        {
            for (int i = 2010; i <= DateTime.Now.Year + 1; i++)
                cmbNamKH.Properties.Items.Add(i.ToString());
            cmbNamKH.Text = DateTime.Now.Year.ToString();
            cmbThangKH.SelectedIndex = DateTime.Now.Month - 1;
            dteNgayTH.DateTime = DateTime.Now;
            pTuanKH = cmbTuanKH.Text + cmbThangKH.Text + cmbNamKH.Text;
        }

        private void fLayGiaTriMauSP()
        {
            pMaMau_SP = "";
            int i = 0;
            while (chkLstMauSP.GetItem(i) != null)
            {
                if (chkLstMauSP.GetItemChecked(i) == true)
                {
                    if (string.IsNullOrEmpty(pMaMau_SP) == false)
                        pMaMau_SP = pMaMau_SP + "','";
                    pMaMau_SP = pMaMau_SP + chkLstMauSP.GetItemValue(i);
                }
                i++;
            }
        }

		private void XuatTapTinExcel(string tabName)
        {
            SaveFileDialog saveDlg;
            try
            {
                saveDlg = new SaveFileDialog();
                saveDlg.InitialDirectory = "C:\"";
                saveDlg.Filter = "Excel Files|*.xls";
                saveDlg.FilterIndex = 2;
                if (saveDlg.ShowDialog() == DialogResult.OK)
                {
                    if (tabName == "tabEDC1")
                    {
                        DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
                        grdNhapEDC_View.ExportToXls(saveDlg.FileName, options);
                    }
                    else if (tabName == "tabEDC2")
                    {
                        DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
                        grdXemEDC_View.ExportToXls(saveDlg.FileName, options);
                    }
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                saveDlg = null;
            }
        }
		
        #endregion

        #region "tabEDC1"

        //Đọc SoLSX của điều phối theo tuần KH
        private void fDocLSXTheoTuanKH(string TuanKH)
        {
            DataSet ds = new DataSet();
            ds = clsedc.DocLSXTheoTuanKH(TuanKH);
            lupLSX.Properties.DataSource = ds.Tables[0].DefaultView;
            lupLSX.Properties.ValueMember = "SoLSX";
            lupLSX.Properties.DisplayMember = "SoLSX";
        }

        //Đọc ma mau chiết tính theo lệnh sản xuất
        private void fDocMauChietTinhTheoLSX(string SoLSX)
        {
            clsedc.SoLSX = SoLSX;
            DataSet ds = new DataSet();
            ds = clsedc.DocMauChietTinhTheoLSX();
            chkLstMauSP.DataSource = ds.Tables[0].DefaultView;
            chkLstMauSP.ValueMember = "MaMau_SP";
            chkLstMauSP.DisplayMember = "TenMau_SP";
            pMaMau_SP = "";
        }

        //Đọc chiết tính theo lệnh sản xuất, ngày thực hiện
        private void fDocChietTinhEDCTheoLSX_MauSP(string SoLSX, string MaMau_SP, string NgayTH)
        {
            dtsNhapEDC = new DataSet();
            clsedc.SoLSX = SoLSX;
            clsedc.MaMau_SP = MaMau_SP;
            dtsNhapEDC = clsedc.DocChietTinhEDCTheoLSX(NgayTH);
            grdNhapEDC.DataSource = dtsNhapEDC.Tables[0].DefaultView;

            lblMsg.Visible = false;

            fMoKhoaControl(true);
            clsdc.editGrid(grdNhapEDC_View, false, null);
        }

        // Lưu EDC theo trạng thái
        private Boolean fLuuEDC()
        {
            try
            {
                switch (intTrangThai)
                {
                    case 1: //trang thai = 1: sửa
                        if (dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows.Count > 0)
                        {
                            for (int intRow = 0; intRow < dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows.Count; intRow++)
                            {
                                clsedc = new clsEDC();
                                clsedc.SoLSX = lupLSX.EditValue.ToString();
                                clsedc.MaChietTinhML = int.Parse(dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["MaChietTinhML"].ToString());
                                clsedc.MaSP = dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["MaSP"].ToString();
                                clsedc.NgayTH = Convert.ToDateTime(dteNgayTH.DateTime.ToShortDateString());
                                clsedc.SLKH = float.Parse(dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["ThucHien"].ToString());
                                if (dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["SL_Nhap_Ca1"].ToString() != "")
                                    clsedc.SL_Nhap_Ca1 = float.Parse(dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["SL_Nhap_Ca1"].ToString());
                                if (dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["SL_Nhap_Ca2"].ToString() != "")
                                    clsedc.SL_Nhap_Ca2 = float.Parse(dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["SL_Nhap_Ca2"].ToString());
                                if (dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["SL_Nhap_Ca3"].ToString() != "")
                                    clsedc.SL_Nhap_Ca3 = float.Parse(dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["SL_Nhap_Ca3"].ToString());
                                clsedc.Tong_SL_Nhap = clsedc.SL_Nhap_Ca1 + clsedc.SL_Nhap_Ca2 + clsedc.SL_Nhap_Ca3;
                                clsedc.MaChungLoai_Mousse = dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["MaChungLoai_Mousse"].ToString();
                                clsedc.MaMau_Mousse = dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["MaMau_Mousse"].ToString();
                                clsedc.DoLy = float.Parse(dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["DoLy"].ToString());
                                clsedc.QuiCach = dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["QuiCach"].ToString();
                                clsedc.MaMau_SP = dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["MaMau_SP"].ToString();
                                clsedc.CoSoID = int.Parse(dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["CoSoID"].ToString());
                                clsedc.MaHoaVan_Mousse = int.Parse(dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["MaHoaVan_Mousse"].ToString());
                                clsedc.DvtID = int.Parse(dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["DVTID"].ToString());
                                clsedc.MaCD = dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["MaCD"].ToString();
                                clsedc.DinhMuc = float.Parse(dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["DinhMuc"].ToString());
                                clsedc.DoShore = dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["DoShore"].ToString();
                                clsedc.GhiChuChiTiet = dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["GhiChuChiTiet"].ToString();
                                clsedc.GhiChu = dtsNhapEDC.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["GhiChu"].ToString();
                                clsedc.UserUpdate = clsDungChung.strUser;

                                if (clsedc.LuuEDC() == false)
                                    return false;
                            }
                            return true;
                        }
                        return true;
                    default:
                        return true;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        #endregion

        #region "tabEDC2"

        //Đọc SoLSX của EDC theo tuần KH
        private void fDocLSX_EDCTheoTuanKH(string TuanKH)
        {
            DataSet ds = new DataSet();
            ds = clsedc.DocLSX_EDCTheoTuanKH(TuanKH);
            lupLSX.Properties.DataSource = ds.Tables[0].DefaultView;
            lupLSX.Properties.ValueMember = "SoLSX";
            lupLSX.Properties.DisplayMember = "SoLSX";
        }

        //Đọc màu SP của EDC theo tuần KH
        private void fDocMauSP_EDCTheoLSX(string SoLSX)
        {
            DataSet ds = new DataSet();
            clsedc.SoLSX = SoLSX;
            ds = clsedc.DocMauSP_EDCTheoLSX();
            chkLstMauSP.DataSource = ds.Tables[0].DefaultView;
            chkLstMauSP.ValueMember = "MaMau_SP";
            chkLstMauSP.DisplayMember = "TenMau_SP"; 
            pMaMau_SP = "";
        }


        //Đọc EDC theo lệnh sản xuất, Màu SP
        private void fDocEDCTheoLSX_MauSP(string SoLSX, string MaMau_SP)
        {
            dtsXemEDC = new DataSet();
            clsedc.SoLSX = SoLSX;
            clsedc.MaMau_SP = MaMau_SP;
            dtsXemEDC = clsedc.DocEDCTheoLSX_MauSP();
            grdXemEDC.DataSource = dtsXemEDC.Tables[0].DefaultView;

            fMoKhoaControl(true);
            clsdc.editGrid(grdXemEDC_View, false, null);
        }

        #endregion      
        
        #endregion
    }
}